package controllers;

import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import play.mvc.*;

import models.*;
import play.test.Fixtures;
 
@With(Secure.class)
public class Application extends Controller {

	/**
	 * rendering the index page
	 */
	public static void index() {
		render();
	}

	   /**
     * @author ousama for getting the id
     */
    public static void getId() {
        long id = Security.userid();
        JsonObject json = new JsonObject();
        json.addProperty("res", id);
        renderJSON(json.toString());

    }

    /**
     * this method renders the name of the current user
     */
    public static void getCurrentUser() {
        JsonObject currentUser = new JsonObject();
        currentUser.addProperty("result", Security.connected());
        renderJSON(currentUser.toString());
    }

    /**
     * @Author Ousama tests the view
     */
    public static void ousamaSprintOne() {
        Fixtures.deleteAll();
        IdeaDeveloper dev = new IdeaDeveloper("Ousama", "Ousama", "111",
                "s@gmail.com", "1-1-1990", "cairo");
        dev.save();
        IdeaDeveloper dev3 = new IdeaDeveloper("Tarek", "Tarek", "113",
                "t@gmail.com", "1-1-1990", "cairo");
        dev3.save();
        IdeaDeveloper dev2 = new IdeaDeveloper("Qamar", "Qamar", "112",
                "q@gmail.com", "1-1-1990", "cairo");
        dev2.save();
        OrganizationLead lead = OrganizationLead.create(dev);
        lead.save();
        Organization.create(lead, "org1");
        Organization org = Organization.find("name = ?", "org1").first();
        org.blocked.add(dev3);
        org.save();
        dev3.blockedOrg.add(org);
        dev3.save();
        org.addEntitiy("Ent1", dev);
        Entities ent = Entities.find("name = ?", "Ent1").first();
        ent.blocked.add(dev2);
        ent.save();
        dev2.blockedEnt.add(ent);
        dev2.save();
        org.addEntitiy("Ent2", dev);
        Entities ent2 = Entities.find("name = ?", "Ent2").first();
        /*
         * OrganizationLead leadTwo = OrganizationLead.create(dev2);
         * Organization.create(leadTwo, "org2"); Organization orgTwo =
         * Organization.find("name = ?", "org2").first(); Request req =
         * Request.RequestMe(org, dev2, "JoinOrgFromOrgToDev"); Organizer orgz =
         * Organizer.create(dev3); orgz.save(); ent.managers.add(orgz);
         * ent.save(); orgz.manages.add(ent); orgz.save(); Request reqTwo =
         * Request.RequestMe(ent, dev2, "JoinEntFromDevToEnt"); Request reqThree
         * = Request.RequestMe(orgTwo, dev3, "JoinOrgFromOrgToDev");
         */
        String username = dev.username;
        long id = dev.id;
        render(username, id);
    }

    /**
     * rendering the test page
     */
    public static void MainPage() {
        render();
    }

    /**
     * @author Ousama this method is the helper method between the view and the
     *         Entity Model to create a new One
     * @param entityName
     *            the name of the added Entity
     * @param orgId
     *            the organbizaion where to add the Entity in
     * @param ideaDeveloper
     *            the develper which asks for that action
     */
    public static void addEntity(String entityName, long orgId,
            long ideaDeveloper) {
        Organization org = Organization.findById(orgId);
        IdeaDeveloper dev = null;
        if (ideaDeveloper != -1) {
            dev = IdeaDeveloper.findById(ideaDeveloper);
        } else {
            String connectedUser = Security.connected();
            dev = IdeaDeveloper.find("username=?", connectedUser).first();
        }
        String toReturnString = org.addEntitiy(entityName, dev);
        JsonObject json = new JsonObject();
        json.addProperty("res", toReturnString);
        renderJSON(json.toString());
    }

    /**
     * @author Ousama * this method is the helper method between the view and
     *         the Entity Model to create a new One as subEntitiy
     * @param entityName
     *            the name of the added Entity
     * @param entId
     *            the entitiy where to add the Entity in
     * @param ideaDeveloper
     *            the develper which asks for that action
     */
    public static void addSubEntity(String entityName, long entId,
            long ideaDeveloper) {
        Entities ent = Entities.findById(entId);
        IdeaDeveloper dev = IdeaDeveloper.findById(ideaDeveloper);
        String toReturnString = ent.addEntity(entityName, dev);
        JsonObject json = new JsonObject();
        json.addProperty("res", toReturnString);
        renderJSON(json.toString());
    }

    /**
     * @author Ousama * this method is the helper method between the view and
     *         the Entity Model to delete one
     * @param entId
     *            the deleted entity
     * @param ideaDeveloper
     *            the develper which asks for that action
     */
    public static void deleteEntity(long entId, long ideaDeveloper) {
        Entities ent = Entities.findById(entId);
        Organization org = ent.liesIn;
        IdeaDeveloper dev = IdeaDeveloper.findById(ideaDeveloper);
        try {
            OrganizationLead lead = OrganizationLead.find("ideaDeveloper = ?",
                    dev).first();
            if (org.managers.contains(lead)) {
                ent.delete2();
                JsonObject json = new JsonObject();
                json.addProperty("res", "DONE");
                renderJSON(json.toString());
            } else {
                JsonObject json = new JsonObject();
                json.addProperty("res", "YOU ARE NOT ALLOWED");
                renderJSON(json.toString());
            }
        } catch (Exception exp) {
            JsonObject json = new JsonObject();
            json.addProperty("res", exp.getMessage());
            renderJSON(json.toString());
        }
    }

    /**
     * @author Ousama
     * @param reqId
     * @param ideaDeveloper
     */
    public static void acceptOrgReq(long reqId, long ideaDeveloper) {
        IdeaDeveloper dev = IdeaDeveloper.findById(ideaDeveloper);
        Request req = Request.findById(reqId);
        try {
            if (req.type.equals("JoinOrgFromDevToOrg")) {
                OrganizationLead lead = Organization.find("ideaDeveloper = ?",
                        dev).first();
                if (req.org.managers.contains(lead)) {
                    req.Accept();
                    JsonObject json = new JsonObject();
                    json.addProperty("res", "DONE");
                    renderJSON(json.toString());
                } else {
                    JsonObject json = new JsonObject();
                    json.addProperty("res", "YOU ARE NOT ALLOWED");
                    renderJSON(json.toString());
                }
            } else if (req.type.equals("JoinEntFromDevToEnt")) {
                OrganizationLead lead = Organization.find("ideaDeveloper = ?",
                        dev).first();
                Organizer orgz = Organizer.find("ideaDeveloper = ?", dev).first();
                if (lead != null) {
                    if (req.ent.liesIn.managers.contains(lead)) {
                        req.Accept();
                        JsonObject json = new JsonObject();
                        json.addProperty("res", "DONE");
                        renderJSON(json.toString());
                    } else {
                        JsonObject json = new JsonObject();
                        json.addProperty("res", "YOU ARE NOT ALLOWED");
                        renderJSON(json.toString());
                    }
                } else if (orgz != null) {
                    if (req.ent.managers.contains(orgz)) {
                        req.Accept();
                        JsonObject json = new JsonObject();
                        json.addProperty("res", "DONE");
                        renderJSON(json.toString());
                    } else {
                        JsonObject json = new JsonObject();
                        json.addProperty("res", "YOU ARE NOT ALLOWED");
                        renderJSON(json.toString());
                    }
                } else {
                    JsonObject json = new JsonObject();
                    json.addProperty("res", "YOU ARE NOT ALLOWED");
                    renderJSON(json.toString());
                }
            }
        } catch (Exception exp) {
            JsonObject json = new JsonObject();
            json.addProperty("res", "ERROR OCCURED");
            renderJSON(json.toString());
        }
    }

    /**
     * @author Ousama this method is for getting the managed organizations by a
     *         user asking for that
     * @param id
     *            the id of the idea developer asking for his
     */
    public static void getManagedOrganizations(long id) {
        // JsonObject josn = new JsonObject();
        IdeaDeveloper dev = IdeaDeveloper.findById(id);
        OrganizationLead leader = OrganizationLead.find("ideaDeveloper = ?",
                dev).first();
        if (leader != null) {
            rendering res[] = new rendering[leader.manages.size()];
            for (int i = 0; i < res.length; i++) {
                res[i] = (new rendering(leader.manages.get(i).name,
                        leader.manages.get(i).id));
            }
            renderJSON(res);
        } else {
            renderJSON((new rendering[0]));
        }

    }

    /**
     * @author ousama This method is for getting the managed entities by an
     *         ideadeveloper
     * @param id
     *            the idea developer asking for that entities
     */
    public static void getManagedEntities(long id) {
        try {
            IdeaDeveloper dev = IdeaDeveloper.findById(id);
            OrganizationLead lead = OrganizationLead.find("ideaDeveloper = ?",
                    dev).first();
            Organizer orgz = Organizer.find("ideaDeveloper =?", dev).first();
            ArrayList<rendering> res = new ArrayList<rendering>();
            if (lead != null) {
                for (int i = 0; i < lead.manages.size(); i++) {
                    for (int k = 0; k < lead.manages.get(i).liesIn.size(); k++) {
                        res.add((new rendering(lead.manages.get(i).liesIn.get(k).name
                                + " In "
                                + lead.manages.get(i).name,
                                lead.manages.get(i).liesIn.get(k).id)));
                    }
                }
            }
            if (orgz != null) {
                for (int i = 0; i < orgz.manages.size(); i++) {
                    res.add((new rendering(orgz.manages.get(i).name + " In "
                            + orgz.manages.get(i).liesIn.name, orgz.manages.get(i).id)));
                }
            }
            renderJSON(res);
        } catch (Exception exp) {
            renderJSON(new ArrayList());
        }
    }

    /**
     * @author Ousama This method is helper method for the view to give an
     *         organizationlead all the requests that wasnot seen ill now and
     *         was sent one of his managed organizations
     * @param id
     *            the ideadeveloper asks for that list
     */
    public static void getRequestsRecievedForMyOrgz(long id) {
        IdeaDeveloper dev = IdeaDeveloper.findById(id);
        OrganizationLead lead = OrganizationLead.find("ideaDeveloper = ?", dev).first();
        ArrayList<rendering> res = new ArrayList<rendering>();
        if (lead != null) {
            for (int i = 0; i < lead.manages.size(); i++) {
                for (int k = 0; k < lead.manages.get(i).requests.size(); k++) {
                    if (lead.manages.get(i).requests.get(k).status.equals("New")
                            && (lead.manages.get(i).requests.get(k).type.equals("JoinOrgFromDevToOrg"))) {
                        rendering tempRender = new rendering(
                                "From : "
                                + lead.manages.get(i).requests.get(k).dev.username
                                + " To Organization :"
                                + lead.manages.get(i).name,
                                lead.manages.get(i).requests.get(k).id);
                        res.add(tempRender);
                    }

                }
                for (int j = 0; j < lead.manages.get(i).liesIn.size(); j++) {
                    for (int k = 0; k < lead.manages.get(i).liesIn.get(j).requests.size(); k++) {
                        if (lead.manages.get(i).liesIn.get(j).requests.get(k).status.equals("New")
                                && (lead.manages.get(i).liesIn.get(j).requests.get(k).type.equals("JoinEntFromDevToEnt"))) {
                            rendering tempRender = new rendering(
                                    "From : "
                                    + lead.manages.get(i).requests.get(k).dev.username
                                    + " To Entity : "
                                    + lead.manages.get(i).liesIn.get(j).name
                                    + " In Organization : "
                                    + lead.manages.get(i).name,
                                    lead.manages.get(i).liesIn.get(j).requests.get(k).id);
                            res.add(tempRender);
                        }
                    }
                }
            }
        }
        Organizer orgz = Organizer.find("ideaDeveloper = ?", dev).first();
        if (orgz != null) {
            for (int j = 0; j < orgz.manages.size(); j++) {
                for (int k = 0; k < orgz.manages.get(j).requests.size(); k++) {
                    if (orgz.manages.get(j).requests.get(k).status.equals("New")
                            && (orgz.manages.get(j).requests.get(k).type.equals("JoinEntFromDevToEnt"))) {
                        rendering tempRender = new rendering(
                                "From : "
                                + orgz.manages.get(j).requests.get(k).dev.username
                                + " To Entity : "
                                + orgz.manages.get(j).name
                                + " In Organization : "
                                + orgz.manages.get(j).liesIn.name,
                                orgz.manages.get(j).requests.get(k).id);
                        res.add(tempRender);
                    }
                }
            }
        }
        renderJSON(res);
    }

    /**
     * @author Ousama This method is the middile between the view and the model
     *         reauest to accept a request
     * @param reqId
     *            the id of the request that will be accepted or declined
     */
    public static void acceptRequest(long reqId) {
        Request req = Request.findById(reqId);
        JsonObject json = new JsonObject();
        json.addProperty("res", req.Accept());
        renderJSON(json.toString());
    }

    /**
     * @author Ousama this method is getting the developers that can be invited
     *         to a certain organization they are not blocked neither joined
     *         already or blocked from an entity inside in or leader for it or
     *         organizer for an entitiy inside it
     * @param orgId
     *            the organization id that we want to invite some users to it
     */
    public static void getCanRequestIdeaDevelopersToOrganization(long orgId) {
        Organization org = Organization.findById(orgId);
        List<IdeaDeveloper> allDevelopers = IdeaDeveloper.findAll();
        List<IdeaDeveloper> blockedDevelopers = org.blocked;
        List<IdeaDeveloper> joinedDevelopers = org.members;
        allDevelopers.removeAll(blockedDevelopers);
        allDevelopers.removeAll(joinedDevelopers);
        ArrayList<IdeaDeveloper> leadersAndOrganizers = new ArrayList<IdeaDeveloper>();
        ArrayList<rendering> rendering = new ArrayList<rendering>();
        for (int i = 0; i < org.managers.size(); i++) {
            leadersAndOrganizers.add(org.managers.get(i).ideaDeveloper);
        }
        for (int i = 0; i < org.liesIn.size(); i++) {
            allDevelopers.removeAll(org.liesIn.get(i).blocked);
            for (int j = 0; j < org.liesIn.get(i).managers.size(); j++) {
                leadersAndOrganizers.add(org.liesIn.get(i).managers.get(j).ideaDeveloper);
            }
        }
        for (int i = 0; i < org.requests.size(); i++) {
            if (org.requests.get(i).type.equals("JoinOrgFromOrgToDev")
                    || org.requests.get(i).type.equals("JoinIdeaDeveloper")) {
                allDevelopers.remove(org.requests.get(i).dev);
                // rendering.add((new rendering(org.requests.get(i).dev.username
                // + " ALREADY INVITED ", (long) -1)));
            }
        }
        allDevelopers.removeAll(leadersAndOrganizers);

        for (int i = 0; i < allDevelopers.size(); i++) {
            rendering.add((new rendering(allDevelopers.get(i).username,
                    allDevelopers.get(i).id)));
        }
        String result = "";
        for (int i = 0; i < rendering.size() - 1; i++) {
            result += rendering.get(i).name + "&";
        }
        JsonObject json = new JsonObject();
        result += rendering.get(rendering.size() - 1).name;
        json.addProperty("result", result);
        renderJSON(json.toString());

    }

    /**
     * @author Ousama
     * @param devName
     *            the developer name that will be requested to join the
     *            organization
     * @param orgId
     *            the Organization which will be the developer requested to
     */
    public static void requestIdeaDeveloperToOrganization(String devName,
            long orgId, String type) {
        Organization org = Organization.findById(orgId);
        IdeaDeveloper dev = IdeaDeveloper.find("username = ?", devName).first();
        JsonObject json = new JsonObject();
        if (dev == null) {
            json.addProperty("res", "INVALID USER");
        } else {
            boolean found = false;
            for (int i = 0; i < dev.requests.size(); i++) {
                if (dev.requests.get(i).org != null
                        && dev.requests.get(i).org.equals(org)
                        && dev.requests.get(i).type.equals(type)) {
                    json.addProperty("res", "ALREADY INVITED");
                    found = true;
                    break;
                }
            }
             for(int i = 0 ; !found && type.equals("JoinOrgFromOrgToDev") && i < org.members.size();i++){
                if(org.members.get(i).equals(dev)){
                    json.addProperty("res", "ALREADY A MEMBER");
                    found = true;
                    break;
                }
            }
             for(int i = 0 ; !found && type.equals("JoinOrgFromOrgToDev") && i < org.managers.size();i++){
                if(org.managers.get(i).ideaDeveloper.equals(dev)){
                    json.addProperty("res", "ALREADY A MANAGER");
                    found = true;
                    break;
                }
            }
            for(int i = 0 ; !found && type.equals("JoinIdeaDeveloper") && i <org.managers.size();i++){
                if(org.managers.get(i).ideaDeveloper.equals(dev)){
                    json.addProperty("res", "ALREADY A MANAGER");
                    found = true;
                    break;
                }
            }
            if (!found) {
                Request req = Request.RequestMe(org, dev, type);
                json.addProperty("res", "DONE");
            }
        }
        renderJSON(json.toString());
    }

    /**
     * @author Ousama
     * @param devName
     *            the developer name that will be requested to join the entity
     * @param entId
     *            the entity which will be the developer requested to
     */
    public static void requestIdeaDeveloperToEntity(String devName, long entId,
            String type) {
        Entities ent = Entities.findById(entId);
        IdeaDeveloper dev = IdeaDeveloper.find("username = ?", devName).first();
        JsonObject json = new JsonObject();
        if (dev == null) {
            json.addProperty("res", "INVALID USER");
        } else {
            boolean found = false;
            for (int i = 0; i < dev.requests.size(); i++) {
                if (dev.requests.get(i).ent != null
                        && dev.requests.get(i).ent.equals(ent)
                        && dev.requests.get(i).type.equals(type)) {
                    json.addProperty("res", "ALREADY INVITED");
                    found = true;
                    break;
                }
            }
            for(int i = 0 ; !found && type.equals("JoinEntFromEntToDev")  && i < ent.members.size();i++){
                if(ent.members.get(i).equals(dev)){
                    json.addProperty("res", "ALREADY A MEMBER");
                    found = true;
                    break;
                }
            }
            for(int i = 0 ; !found && type.equals("JoinEntFromEntToDev") && i < ent.managers.size();i++){
                if(ent.managers.get(i).ideaDeveloper.equals(dev)){
                    json.addProperty("res", "ALREADY A MANAGER");
                    found = true;
                    break;
                }
            }
            for(int i = 0 ; !found && type.equals("JoinIdeaDeveloper") && i < ent.managers.size();i++){
                if(ent.managers.get(i).ideaDeveloper.equals(dev)){
                    json.addProperty("res", "ALREADY A MANAGER");
                    found = true;
                    break;
                }
            }
            if (!found) {
                Request req = Request.RequestMe(ent, dev, type);
                json.addProperty("res", "DONE");
            }

        }
        renderJSON(json.toString());
    }

    /**
     * @author Ousama this method retretives the develops that can be invited to
     *         the requested entity
     * @param entId
     *            the id of the entity that we want to invite a developer to it
     */
    public static void getCanRequestIdeaDevelopersToEntity(long entId) {
        Entities ent = Entities.findById(entId);
        Organization org = ent.liesIn;
        List<IdeaDeveloper> allDevelopers = IdeaDeveloper.findAll();
        List<IdeaDeveloper> blockedDevelopers = org.blocked;
        allDevelopers.removeAll(blockedDevelopers);
        ArrayList<IdeaDeveloper> leadersAndOrganizers = new ArrayList<IdeaDeveloper>();
        ArrayList<rendering> rendering = new ArrayList<rendering>();
        for (int i = 0; i < org.managers.size(); i++) {
            leadersAndOrganizers.add(org.managers.get(i).ideaDeveloper);
        }
        for (int i = 0; i < ent.managers.size(); i++) {
            leadersAndOrganizers.add(ent.managers.get(i).ideaDeveloper);
        }
        for (int i = 0; i < ent.requests.size(); i++) {
            if (ent.requests.get(i).type.equals("JoinEntFromEntToDev")
                    || ent.requests.get(i).type.equals("JoinIdeaDeveloper")) {
                allDevelopers.remove(ent.requests.get(i).dev);
                // rendering.add((new rendering(ent.requests.get(i).dev.username
                // + " ALREADY INVITED ", (long) -1)));
            }
        }
        allDevelopers.removeAll(leadersAndOrganizers);
        allDevelopers.removeAll(ent.blocked);
        allDevelopers.removeAll(ent.members);
        for (int i = 0; i < allDevelopers.size(); i++) {
            rendering.add((new rendering(allDevelopers.get(i).username,
                    allDevelopers.get(i).id)));
        }

        String result = "";
        for (int i = 0; i < rendering.size() - 1; i++) {
            result += rendering.get(i).name + "&";
        }
        JsonObject json = new JsonObject();
        result += rendering.get(rendering.size() - 1).name;
        json.addProperty("result", result);
        renderJSON(json.toString());

    }

    /**
     * @author Ousama this method for retrievng the request sent to the
     *         developer and was not yet accepted
     * @param devId
     *            the developer which we want to get the requestst sent to him
     */
    /**
     * @author Ousama this method for retrievng the request sent to the
     *         developer and was not yet accepted
     * @param devId
     *            the developer which we want to get the requestst sent to him
     */
    public static void getRequestsSentToIdeaDeveloper(long devId) {
        IdeaDeveloper dev = IdeaDeveloper.findById(devId);
        ArrayList<rendering> reqs = new ArrayList<rendering>();
        for (int i = 0; i < dev.requests.size(); i++) {
            if (dev.requests.get(i).status.equals("New")) {
                if ((dev.requests.get(i).type.equals("JoinOrgFromOrgToDev") || dev.requests.get(i).type.equals("JoinIdeaDeveloper"))
                        && dev.requests.get(i).org != null) {
                    String whatRequest = "";
                    if(dev.requests.get(i).type.equals("JoinOrgFromOrgToDev"))
                            whatRequest = "you are invited to be a member";
                    else
                            whatRequest = "you are invited to be a leader";
                    reqs.add((new rendering("From Organization : "
                            + dev.requests.get(i).org.name+" "+whatRequest,
                            dev.requests.get(i).id)));
                } else if ((dev.requests.get(i).type.equals("JoinEntFromEntToDev") || dev.requests.get(i).type.equals("JoinIdeaDeveloper"))
                        && dev.requests.get(i).ent != null) {
                    String whatRequest = "";
                    if(dev.requests.get(i).type.equals("JoinEntFromEntToDev"))
                            whatRequest = "you are invited to be a member";
                    else
                            whatRequest = "you are invited to be an organizer";
                    reqs.add((new rendering("From Entity : "
                            + dev.requests.get(i).ent.name
                            + " In Organization : "
                            + dev.requests.get(i).ent.liesIn.name+" "+whatRequest, dev.requests.get(i).id)));
                }
            }
        }

        renderJSON(reqs);
    }

	public static void RestrictOrganizerEntity() {
		IdeaDeveloper i1 = new IdeaDeveloper();
		IdeaDeveloper i2 = new IdeaDeveloper();
		IdeaDeveloper i3 = new IdeaDeveloper();
		Organization o = new Organization();
		OrganizationLead OL = new OrganizationLead();
		Organizer z1 = new Organizer();
		Organizer z2 = new Organizer();
		Organizer z3 = new Organizer();
		Entities e1 = new Entities();
		Entities e2 = new Entities();
		Topic t = new Topic();

		i1.username = "omar1";
		i1.fullName = "omar1";
		i1.eMail = "omar1";
		i1.dateOfBirth = "omar1";
		i1.password = "omar1";
		i1.passwordHash = "omar1";
		i1.address = "omar1";
		i1.save();

		i2.username = "gebna1";
		i2.fullName = "gebna1";
		i2.eMail = "gebna1";
		i2.dateOfBirth = "gebna1";
		i2.password = "gebna1";
		i2.passwordHash = "gebna1";
		i2.address = "gebna1";
		i2.save();

		i3.username = "Alien1";
		i3.fullName = "Alien1";
		i3.eMail = "Alien1";
		i3.dateOfBirth = "Alien1";
		i3.password = "Alien1";
		i3.passwordHash = "Alien1";
		i3.address = "Alien1";
		i3.save();

		OL.ideaDeveloper = i1;
		o.name = "organization dddd";
		OL.save();
		o.creator = OL;
		o.managers.add(OL);

		o.liesIn.add(e1);
		o.liesIn.add(e2);
		OL.manages.add(o);
		z1.ideaDeveloper = i2;
		z2.ideaDeveloper = i1;
		z3.ideaDeveloper = i3;

		z1.manages.add(e1);
		z1.manages.add(e2);
		z2.manages.add(e1);
		z2.manages.add(e2);
		z2.managedTopics.add(t);
		z3.managedTopics.add(t);

		e1.liesIn = o;
		e1.name = "Eentity11";
		e1.managers.add(z1);
		e1.managers.add(z2);

		e2.liesIn = o;
		e2.name = "Eentity22";
		e2.managers.add(z1);
		e2.managers.add(z2);
		t.hidden = false;
		t.title = "topic";
		t.description = "wazzzaaa";
		t.dateOfDraftingPosting = new java.util.Date();
		t.managers.add(z1);
		t.topicOrg = o;
		t.topicEnt = e1;
		t.managers.add(z2);
		z1.managedTopics.add(t);
		z2.managedTopics.add(t);
		o.topics.add(t);
		z3.managedTopics.add(t);
		o.save();

		z1.save();
		z2.save();
		z3.save();
		e2.save();
		t.save();
		e1.save();
		String topicID = t.id.toString();
		String entityID = e1.id.toString();
		String leadID = OL.id.toString();
		String eID = e2.id.toString();
		render(topicID, leadID, entityID, eID);
	}

	/**
	 * restricts an organizer to a entity by removing this organizer from
	 * organizing any other entity or topic in this organization
	 * 
	 * @author Omar el alfy
	 * @param entityID
	 *            entity id to be restricted to
	 * @param organizerName
	 *            organizer username to be restricted
	 */
	public static void resOrganizersEntity(long entityID, String organizerName) {
		JsonObject json = new JsonObject();
		Organizer organizer = new Organizer();
		Entities entity = Entities.find("id =?", entityID).first();
		for (int i = 0; i < Organizer.findAll().size(); i++) {
			if ((((Organizer) Organizer.findAll().get(i)).ideaDeveloper.username)
					.equals(organizerName)) {
				organizer = (Organizer) Organizer.findAll().get(i);
				break;
			}
		}
		json.addProperty("res",
				OrganizationLead.restrictAccessEntity(organizer, entity));
		Notification.notify(
				"has restricted you to entity : " + entity.name,
				organizer.ideaDeveloper,
				(IdeaDeveloper) IdeaDeveloper.find("username=?",
						Security.connected()).first(), new Date());
		renderJSON(json.toString());
	}

	/**
	 * restricts an organizer to a entity by removing this organizer from
	 * organizing any other entity or topic in this organization
	 * 
	 * @author Omar el alfy
	 * @param entityID
	 *            entity id to be restricted to
	 * @param organizerName
	 *            organizer username to be restricted
	 */
	public static void getOrganizersEntity(long entityID) {
		JsonObject json = new JsonObject();
		String result = "*";
		try {
			Entities entity = Entities.find("id =?", entityID).first();

			for (int i = 0; i < entity.managers.size(); i++) {
				if (!result
						.contains(entity.managers.get(i).ideaDeveloper.username)) {
					json.addProperty("orgID",
							entity.managers.get(i).id.toString());
					result += entity.managers.get(i).ideaDeveloper.username
							+ "*";
				}
			}
		} catch (Exception e) {
			json.addProperty("res", "matrunesh");
		}
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	public static void makeLead() {
		IdeaDeveloper i1 = new IdeaDeveloper();
		IdeaDeveloper i2 = new IdeaDeveloper();
		IdeaDeveloper i3 = new IdeaDeveloper();
		Organization o = new Organization();
		OrganizationLead OL = new OrganizationLead();
		Organizer z1 = new Organizer();
		Organizer z2 = new Organizer();
		Organizer z3 = new Organizer();
		Entities e1 = new Entities();
		Entities e2 = new Entities();
		Topic t = new Topic();

		i1.username = "omar1";
		i1.fullName = "omar1";
		i1.eMail = "omar1";
		i1.dateOfBirth = "omar1";
		i1.password = "omar1";
		i1.passwordHash = "omar1";
		i1.address = "omar1";
		i1.save();

		i2.username = "gebna1";
		i2.fullName = "gebna1";
		i2.eMail = "gebna1";
		i2.dateOfBirth = "gebna1";
		i2.password = "gebna1";
		i2.passwordHash = "gebna1";
		i2.address = "gebna1";
		i2.save();

		i3.username = "Alien1";
		i3.fullName = "Alien1";
		i3.eMail = "Alien1";
		i3.dateOfBirth = "Alien1";
		i3.password = "Alien1";
		i3.passwordHash = "Alien1";
		i3.address = "Alien1";
		i3.save();

		OL.ideaDeveloper = i1;
		o.name = "organization dddd";
		OL.save();
		o.creator = OL;
		o.managers.add(OL);

		o.liesIn.add(e1);
		o.liesIn.add(e2);
		OL.manages.add(o);
		z1.ideaDeveloper = i2;
		z2.ideaDeveloper = i1;
		z3.ideaDeveloper = i3;
		z1.manages.add(e1);
		z1.manages.add(e2);
		z2.manages.add(e1);
		z2.manages.add(e2);
		z3.managedTopics.add(t);

		e1.liesIn = o;
		e1.name = "Eentity11";
		e1.managers.add(z1);
		e1.managers.add(z2);

		e2.liesIn = o;
		e2.name = "Eentity22";
		e2.managers.add(z1);
		e2.managers.add(z2);

		t.hidden = false;
		t.title = "topic";
		t.description = "wazzzaaa";
		t.dateOfDraftingPosting = new java.util.Date();
		t.managers.add(z1);
		t.topicOrg = o;
		t.managers.add(z3);
		t.topicEnt = e1;
		z1.managedTopics.add(t);
		o.topics.add(t);
		z3.managedTopics.add(t);
		o.save();
		z1.save();
		z2.save();
		z3.save();
		e2.save();
		t.save();
		e1.save();
		String orgID = o.id.toString();
		render(orgID);
	}

	/**
	 * get list of organizers on any entity or topic in an organization
	 * 
	 * @param orgID
	 *            organization id
	 */
	public static void getAllOrganizers(long orgID) {
		List<Entities> listOfEntities = new ArrayList<Entities>();
		List<Topic> listOfTopics = new ArrayList<Topic>();
		JsonObject json = new JsonObject();
		String s = "*";

		try {
			Organization t = Organization.find("id =?", orgID).first();
			listOfEntities = t.liesIn;
			listOfTopics = t.topics;
			for (int j = 0; j < listOfEntities.size(); j++) {
				Entities E = listOfEntities.get(j);
				for (int i = 0; i < E.managers.size(); i++) {
					if (!s.contains(E.managers.get(i).ideaDeveloper.username)) {
						if (OrganizationLead.count("ideaDeveloper=?",
								E.managers.get(i).ideaDeveloper) == 0) {
							s += E.managers.get(i).ideaDeveloper.username + "*";
						}
					}
				}
			}
			for (int j = 0; j < listOfTopics.size(); j++) {
				Topic T = listOfTopics.get(j);
				for (int i = 0; i < T.managers.size(); i++) {
					if (!s.contains(T.managers.get(i).ideaDeveloper.username)) {
						if (OrganizationLead.count("ideaDeveloper=?",
								T.managers.get(i).ideaDeveloper) == 0) {
							s += T.managers.get(i).ideaDeveloper.username + "*";
						}
					}
				}
			}

		} catch (Exception e) {
			json.addProperty("res", "exeption");
		}
		json.addProperty("res", s);

		renderJSON(json.toString());
	}

	/**
	 * makes an organizer an organization lead
	 * 
	 * @author Omar el alfy
	 * @param orgID
	 *            organization to become lead on
	 * @param organizerUsername
	 *            username of an organizer to become lead
	 */
	public static void makeOrganizationLead(long orgID, String organizerUsername) {
		JsonObject json = new JsonObject();
		String result = "";
		Organizer organizer = null;
		Organization organization = Organization.find("id =?", orgID).first();
		json.addProperty("org", organization.name);
		for (int i = 0; i < Organizer.findAll().size(); i++) {
			if ((((Organizer) Organizer.findAll().get(i)).ideaDeveloper.username)
					.equals(organizerUsername)) {
				organizer = (Organizer) Organizer.findAll().get(i);
				break;
			}
		}
		OrganizationLead.makeOrganizationLead(organization, organizer);
		result = organizerUsername + " is now Lead";
		json.addProperty("res", result);
		Notification.notify(
				"has promoted you to an org lead for organization : "
						+ organization.name,
				organizer.ideaDeveloper,
				(IdeaDeveloper) IdeaDeveloper.find("username=?",
						Security.connected()).first(), new Date());
		renderJSON(json.toString());
	}

	public static void testLead(long orgID) {
		JsonObject json = new JsonObject();
		String s = "*";
		try {
			Organization t = Organization.find("id =?", orgID).first();

			for (int i = 0; i < t.managers.size(); i++) {

				s += t.managers.get(i).ideaDeveloper.username + "*";
			}
		} catch (Exception e) {
			json.addProperty("res", "matrunesh");
		}
		json.addProperty("res", s);

		renderJSON(json.toString());
	}

	/**
	 * checks if the idea developer already follows this organization or not
	 * 
	 * @author nataly.wadie
	 * @param organizationId
	 *            id of the organization that the idea developer wants to follow
	 */
	public static void canFollowOrganization(long organizationId) {
		Organization organization = Organization.findById(organizationId);
		String follower = Security.connected();
		IdeaDeveloper organizationFollower = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		JsonObject checkFollow = new JsonObject();
		if (!Organization.followCheck(organizationFollower, organization)) {
			checkFollow.addProperty("followOrganization", "can follow");
			renderJSON(checkFollow.toString());
		}
		if (Organization.followCheck(organizationFollower, organization)) {
			checkFollow.addProperty("followOrganization",
					"you are already a follower");
			renderJSON(checkFollow.toString());
		}
	}

	/**
	 * makes sure that the user is not already a follower to this organization
	 * and adds him to the list of followers of the organization and adds the
	 * organization to the list of organizations followed by this user
	 * 
	 * @author nataly.wadie
	 * @param organizationId
	 *            id of organization that the idea developer wants to follow
	 */
	public static void followOrganization(long organizationId) {
		String follower = Security.connected();
		IdeaDeveloper organizationFollower = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		Organization organization = Organization.findById(organizationId);
		JsonObject followOrganization = new JsonObject();
		if (!Organization.followCheck(organizationFollower, organization)) {
			Organization.followOrganization(organizationFollower, organization);
		}
		followOrganization.addProperty("followOrganization",
				"successfully followed");
		renderJSON(followOrganization.toString());
	}

	/**
	 * makes sure that the user is already a follower and removes him from the
	 * list of followers of this organization and removes the organization from
	 * the list of followed organizations of the user
	 * 
	 * @author nataly.wadie
	 * @param organizationId
	 *            the id of the organization that is going to be unfollowed by
	 *            the user
	 */
	public static void unfollowOrganization(long organizationId) {
		String follower = Security.connected();
		IdeaDeveloper organizationFollower = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		Organization organization = Organization.findById(organizationId);
		JsonObject unfollowOrganization = new JsonObject();
		if (Organization.followCheck(organizationFollower, organization)) {
			Organization.unfollowOrganization(organizationFollower,
					organization);
		}
		unfollowOrganization.addProperty("unfollowOrganization",
				"successfully unfollowed");
		renderJSON(unfollowOrganization.toString());
	}

	/**
	 * sends a topic request to the organization
	 * 
	 * @author Dina
	 * 
	 * @param title
	 *            title proposed in the topic request
	 * @param description
	 *            description proposed in the topic request
	 * @param orgId
	 *            the id of the organization
	 */
	public static void topicRequestOrg(String title, String description,
			long orgId) {
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		Organization org = Organization.findById(orgId);
		Request.RequestMe(org, idev, title, description);
		int s = (Request.find(
				"title=? and description=? and orgId=? and dev=?", title,
				description, orgId, idev).fetch()).size();
		if (s != 0) {
			Request r = (Request) Request
					.find("title=? and description=? and orgId=? and dev=?",
							title, description, orgId, idev).fetch().get(0);
			if (r != null) {
				r.delete2();
			}
		}
	}

	/**
	 * checks if the topic request is saved in the organization
	 * 
	 * @author Dina
	 * 
	 * @param orgId
	 *            the organization id
	 */
	public static void topicRequestOrgSaved(long orgId) {
		// IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		JsonObject check = new JsonObject();
		Organization org = Organization.findById(orgId);
		check.addProperty("RequestsinOrg", org.requests.size());
		renderJSON(check.toString());
	}

	/**
	 * @author AbedelRahman Badawy renders the idea developers of the
	 *         organization giver
	 * 
	 * @param orgId
	 *            the organization where its developers are rendered
	 * @return true if successful , false if failure
	 */
	public static boolean developersOfOrganization(long orgId) {

		Organization org = (Organization) Organization.find("id=?", orgId)
				.fetch().get(0);
		if (org != null) {
			List developers = org.members;

			render(developers);
			return true;
		}
		return false;

	}

	/**
	 * save a topic request draft in an organization
	 * 
	 * @author Dina
	 * 
	 * @param title
	 *            title of the drafted topic request
	 * @param description
	 *            description of the drafted topic request
	 * @param orgId
	 *            id of the organization the topic request is drafted in
	 */
	public static void saveDraft(String title, String description, long orgId) {
		IdeaDeveloper dev = IdeaDeveloper.findById(Security.userid());
		Request.draftMeOrg(title, description, dev, orgId);
	}

	/**
	 * check the number of drafted topic requests
	 * 
	 * @author Dina
	 */
	public static void checkDraftSaved() {
		IdeaDeveloper dev = IdeaDeveloper.findById(Security.userid());
		JsonObject checkDraft = new JsonObject();
		int noreqs = Request.find("dev=? and type=?", dev, "TopicDraft")
				.fetch().size();
		Request r = (Request) Request
				.find("dev=? and type=?", dev, "TopicDraft").fetch()
				.get(noreqs - 1);
		checkDraft.addProperty("draftedTitle", r.title);
		checkDraft.addProperty("draftedBody", r.description);
		renderJSON(checkDraft.toString());
	}

	/**
	 * check the connected user is one of the leaders or just an enrolled
	 * ideaDeveloper
	 * 
	 * @author Dina
	 * @param orgId
	 *            id of the organization where the user is logged in
	 */
	public static void checkForButtons(long orgId) {
		IdeaDeveloper dev = IdeaDeveloper.findById(Security.userid());
		Organization org = Organization.findById(orgId);
		JsonObject checkButtons = new JsonObject();
		ArrayList<IdeaDeveloper> leads = new ArrayList<IdeaDeveloper>();
		for (int i = 0; i < org.managers.size(); i++) {
			leads.add(org.managers.get(i).ideaDeveloper);
		}
		checkButtons.addProperty("leaders", leads.contains(dev));
		renderJSON(checkButtons.toString());
	}

	/**
	 * get the requests of a certain organization and is sent to the views in a
	 * JsonObject
	 * 
	 * @author Dina
	 * 
	 * @param orgId
	 *            id of the organization
	 * @param x
	 *            the index of the requests in the requests list of that
	 *            organization
	 */
	public static void getRequests(long orgId, long x) {
		Organization org = Organization.findById(orgId);
		int i = (int) x;
		JsonObject json = new JsonObject();
		json.addProperty("size", org.requests.size());
		if (!org.requests.isEmpty()) {
			Request r = org.requests.get(i);
			json.addProperty("x", i);
			json.addProperty("name", r.dev.username);
			json.addProperty("title", r.title);
			json.addProperty("description", r.description);
			json.addProperty("id", r.id);
		}
		renderJSON(json.toString());

	}

	/**
	 * renders the organization view template and fills all the data including
	 * managers,creator,ideas,topics,entites
	 * 
	 * @param name
	 * @author XtarX
	 */
	public static void OrganizationView(String name) {
		Organization organization = Organization.find("name=?", name).first();
		List managers = organization.managers;
		//List ideas = organization.ideas;
		List entites = organization.liesIn;
		boolean canLeadOrg;
		List memebers = organization.members;
		long orgId = organization.id;
		List followers = organization.followed;
		Long loggedUserId = Security.userid();
		String loggedInUserName = Security.connected();
		String type = "org";
		IdeaDeveloper loggedUserIdeaDev = IdeaDeveloper.findById(loggedUserId);
		List topics = BrowseController.viewTopicsInsideOrg(organization, loggedUserIdeaDev);
		List ideas=	BrowseController.viewIdeasInsideOrg(organization, loggedUserIdeaDev);
		List draftedIdeas = Idea.find(
				"published=? and ideaOrg=? and creator.id=?", false,
				organization, loggedUserId).fetch();
		List draftedTopics = Topic.find(
				"published=? and topicOrg=? and creator.id=?", false,
				organization, loggedUserId).fetch();
		OrganizationLead organizationlead = OrganizationLead.find(
				"ideaDeveloper=?", loggedUserIdeaDev).first();
		boolean isLead = organizationlead != null
				&& (organizationlead.createdOrgs.contains(organization) || organizationlead.manages
						.contains(organization));
		boolean isCreator = organization.creator.ideaDeveloper.id == loggedUserId;
		// boolean isCreatororIsisLead = isCreator || isLead;
		// @{UserProfile.OtherUserProfile(${})}
		// String creatorName = organization.creator.ideaDeveloper.username;
		// boolean isMemeber= organization.find("memebers.IdeaDeveloper=? ",
		// loggedUserIdeaDev).first()!= null;
		boolean isPublic = organization.type.equalsIgnoreCase("public");
		boolean isSecret = organization.type.equalsIgnoreCase("secret");
		boolean canview = IdeaDeveloper.canViewOrganizationForOrganizationView(
				loggedUserIdeaDev, organization) || isPublic;
		boolean isMemeber = organization.members.contains(loggedUserIdeaDev);
		boolean requestSentBefore = Request.find("dev=? and type=? and org=?",
				loggedUserIdeaDev, "JoinOrgFromDevToOrg", organization).first() != null;
		if (IdeaDeveloper.canLeadOrganization(loggedUserIdeaDev, organization)) {
			canLeadOrg = true;
		} else
			canLeadOrg = false;
		render(orgId, organization, managers, ideas, entites, topics, memebers,
				followers, loggedInUserName, requestSentBefore, type,
				loggedUserId, isPublic, canview, isMemeber, draftedIdeas,
				draftedTopics, isLead, canLeadOrg, isSecret);

	}

	public static void incrementViews(Long id, String type) {

		JsonObject inrementCounter = new JsonObject();

		if (type.equals("organization")) {
			inrementCounter.addProperty("res", Organization.incrementViews(id));
			Organization organization = Organization.findById(id);
			inrementCounter.addProperty("privacy", organization.type);
			renderJSON(inrementCounter.toString());

		}
		if (type.equalsIgnoreCase("topic")) {

			// inrementCounter.addProperty("res", Topic.incrementViews(id));
			// renderJSON(inrementCounter.toString());

		}
		if (type.equalsIgnoreCase("entity")) {
			inrementCounter.addProperty("res", Entities.incrementViews(id));
			renderJSON(inrementCounter.toString());

		}

	}

	/**
	 * rejects a topic requests and delete it from the database
	 * 
	 * @author Dina
	 * 
	 * @param reqId
	 *            the id of the request
	 */
	public static void reqRej(long reqId) {
		Request req = Request.findById(reqId);
		req.delete2();
	}

	/**
	 * gets the counter of a specific ideaDeveloper
	 * 
	 * @author Sameha
	 */

	public static void communityCounter() {
		IdeaDeveloper currentIdeaDeveloper = IdeaDeveloper.find("id=?",
				Security.userid()).first();
		JsonObject json = new JsonObject();
		json.addProperty("Counter", currentIdeaDeveloper.communityCounter);
		renderJSON(json.toString());
	}

	/**
	 * returns my type as a user depending on my community counter
	 * 
	 * @author Sameha
	 */
	public static void typeOfMe() {
		IdeaDeveloper currentIdeaDeveloper = IdeaDeveloper.find("id=?",
				Security.userid()).first();
		JsonObject json = new JsonObject();
		if (currentIdeaDeveloper.communityCounter < 200) {
			json.addProperty("type", "spammer");
		}
		if (currentIdeaDeveloper.communityCounter >= 0
				&& currentIdeaDeveloper.communityCounter <= 150) {
			json.addProperty("type", "beginner");
		}
		if (currentIdeaDeveloper.communityCounter >= 151
				&& currentIdeaDeveloper.communityCounter <= 300) {
			json.addProperty("type", "Intermediate");
		}
		if (currentIdeaDeveloper.communityCounter >= 301
				&& currentIdeaDeveloper.communityCounter <= 500) {
			json.addProperty("type", "Semi Professional");
		}
		if (currentIdeaDeveloper.communityCounter >= 501
				&& currentIdeaDeveloper.communityCounter <= 750) {
			json.addProperty("type", "Profesional");
		}
		if (currentIdeaDeveloper.communityCounter >= 751) {
			json.addProperty("type", "Expert");
		}
		renderJSON(json.toString());
	}

	/**
	 * dispalys the view of the entity and all its components
	 * 
	 * @param entityId
	 *            the entity to be displayed
	 */
	public static void EntityView(Long entityId) {
		Entities entity = Entities.findById(entityId);
		List managers = entity.managers;
		List subEntites = entity.childern;
		List memebers = entity.members;
		List followers = entity.followed;
		String entityName = entity.name;
		Entities parents = entity.parent;
		Long loggedUserId = Security.userid();
		boolean entityisLocked = entity.locked;
                List topics = new ArrayList<Topic>();
                List ideas = new ArrayList<Idea>();
		int canLeadOrg = 0;
		
		List draftedIdeas = Idea.find(
				"published=? and ideaEnt=? and creator.id=?", false, entity,
				loggedUserId).fetch();
		List draftedTopics = Topic.find(
				"published=? and topicEnt=? and creator.id=?", false, entity,
				loggedUserId).fetch();
		int isOrgLead = 0;
		String type = "entity";
		try {
			Organization organizatioEntity = Organization.find("name=?",
					BrowseController.getEntityOrganization(entityName)).first();
			IdeaDeveloper user = IdeaDeveloper.find("username=?",
					Security.connected()).first();
                        topics = BrowseController.viewTopicsInsideEntit(entity, user);
                        ideas = BrowseController.viewIdeasInsideEntit(entity, user);
			if (IdeaDeveloper.canLeadEntity(user, entity)) {
				isOrgLead = 1;
			}
			if (IdeaDeveloper.canLeadOrganization(user, organizatioEntity)) {
				canLeadOrg = 1;
			}
		} catch (Exception e) {
			isOrgLead = 0;
		}
		Organization org = entity.liesIn;
		List EntitiesNames = new ArrayList<String>();
		for (int i = 0; i < org.liesIn.size(); i++) {
			if (!org.liesIn.get(i).equals(entity))
				EntitiesNames.add(org.liesIn.get(i).name);
		}
		List entRelations = EntityRelation
				.find("select tr from EntityRelation tr where tr.firstEntity =? or tr.secondEntity=? ",
						entityId, entityId).fetch();
		List toBeDeleted = new ArrayList<String>();
		for (int i = 0; i < entRelations.size(); i++) {
			EntityRelation y = (EntityRelation) entRelations.get(i);
			Entities one = Entities.findById(y.firstEntity);
			Entities two = Entities.findById(y.secondEntity);
			String d = one.name + " " + y.relationName + " " + two.name;

			toBeDeleted.add(d);
		}

		Organization organization = entity.liesIn;
		render(entityName, managers, ideas, subEntites, topics, memebers,
				followers, entityId, isOrgLead, type, EntitiesNames,
				toBeDeleted, organization, parents, draftedIdeas,
				draftedTopics, canLeadOrg, entityisLocked);
	}

	/**
	 * checks if the idea developer is already following the intended entity or
	 * not
	 * 
	 * @author nataly.wadie
	 * @param follower
	 *            username of the idea developer that wants to follow the entity
	 * @param entity
	 *            id of the entity that the idea developer wants to follow
	 */
	public static void canFollowEntity(long entity) {
		Entities entityToFollow = Entities.findById(entity);
		String follower = Security.connected();
		IdeaDeveloper f = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		JsonObject json = new JsonObject();
		if (!Entities.followCheck(f, entityToFollow)) {
			json.addProperty("followEntity", "can follow");
			renderJSON(json.toString());
		}
		if (Entities.followCheck(f, entityToFollow)) {
			json.addProperty("followEntity", "you are already a follower");
			renderJSON(json.toString());
		}
	}

	/**
	 * makes sure that the idea developer is already a follower to the specific
	 * entity then implements the unfollowEntity method to remove the follower
	 * from the database
	 * 
	 * @author nataly.wadie
	 * @param entity
	 *            the entity id that is going to be unfollowed by the user
	 */
	public static void unfollowEntity(long entity) {
		String follower = Security.connected();
		IdeaDeveloper follower2 = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		Entities entityToUnfollow = Entities.findById(entity);
		JsonObject json = new JsonObject();
		if (Entities.followCheck(follower2, entityToUnfollow)) {
			Entities.unfollowEntity(follower2, entityToUnfollow);
		}
		json.addProperty("unfollowEntity", "successfully unfollowed");
		renderJSON(json.toString());
	}
        /**
	 * lock or unlock relation depending on the type if lock it will lock the
	 * topic from being in a relataion,else it will unlock the entity thus can be
	 * in relation with another entities
	 * @author mohamed tarek
	 * @param entityId
	 * the entity to be locked/unlocked id
	 * @param type
	 * the type lock or unlock the topic
	 * @return void
	 */
	public static void lockOrUnlockEntity(Long entityId, String type) {
		JsonObject lockorUnlockResponse = new JsonObject();
		Entities entity = Entities.find("id=?", entityId).first();
		String user = Security.connected();
		IdeaDeveloper locker = (IdeaDeveloper) IdeaDeveloper.find("username=?", user).first();
		
		if (type.equals("lock")) {
			for(int i=0; i<entity.followed.size(); i++){
				Notification.notify(" has locked the entity <a href='/application/entityview?entityId="
								+ entity.id + "'>" + entity.name + "</a>", entity.followed.get(i), locker, new Date());
			}
			lockorUnlockResponse.addProperty("res",
					Entities.lockEntity(entityId));
			renderJSON(lockorUnlockResponse.toString());

		} else {
			for(int i=0; i<entity.followed.size(); i++){
				Notification.notify(" has unlocked the entity <a href='/application/entityview?entityId="
						+ entity.id + "'>" + entity.name + "</a>", entity.followed.get(i), locker, new Date());
			}
			lockorUnlockResponse.addProperty("res",
					Entities.unlockEntity(entityId));
			renderJSON(lockorUnlockResponse.toString());
		}

	}

	/**
	 * makes sure that the idea developer is not a follower to the specific
	 * entity and then calls the method followEntity to add the follower to the
	 * database
	 * 
	 * @author nataly.wadie
	 * @param follower
	 *            username of idea developer that wants to follow the entity
	 * @param entity
	 *            id of the entity that the idea developer wants to follow
	 */
	public static void followEntity(long entity) {
		String follower = Security.connected();
		IdeaDeveloper entityFollower = (IdeaDeveloper) IdeaDeveloper
				.find("username=?", follower).fetch().get(0);
		Entities entityToFollow = Entities.findById(entity);
		JsonObject json = new JsonObject();
		if (!Entities.followCheck(entityFollower, entityToFollow)) {
			Entities.followEntity(entityFollower, entityToFollow);
		}
		json.addProperty("followEntity", "successfully followed");
		renderJSON(json.toString());
	}

	/**
	 * 
	 * check whether the drafts list in an organization is empty or not and
	 * sends to the view in JsonObject
	 * 
	 * @author Dina
	 * 
	 * @param orgId
	 *            id of the organization the user is logged on in
	 */
	public static void draftsButtons(long orgId) {
		Organization org = Organization.findById(orgId);
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		ArrayList<Request> drafts = new ArrayList<Request>();
		for (int i = 0; i < idev.requests.size(); i++) {
			if (idev.requests.get(i).type.equals("TopicDraft")) {
				drafts.add(idev.requests.get(i));
			}
		}
		JsonObject json = new JsonObject();
		json.addProperty("draftsEmpty", drafts.isEmpty());
		renderJSON(json.toString());
	}

	/**
	 * gets the draft of index x in the list of drafts in a certain organization
	 * 
	 * @param orgId
	 *            id of the organization
	 * @param x
	 *            index of the request in the drafts list
	 */
	public static void getDrafts(long orgId, long x) {
		Organization org = Organization.findById(orgId);
		int y = (int) x;
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		ArrayList<Request> drafts = new ArrayList<Request>();
		for (int i = 0; i < idev.requests.size(); i++) {
			if (idev.requests.get(i).type.equals("TopicDraft")
					&& idev.requests.get(i).orgId == org.id) {
				drafts.add(idev.requests.get(i));
			}
		}
		Request r = drafts.get(y);
		JsonObject json = new JsonObject();
		json.addProperty("size", drafts.size());
		json.addProperty("title", r.title);
		json.addProperty("description", r.description);
		json.addProperty("id", r.id);
		renderJSON(json.toString());
	}

	public static void removeDraft(long draftId) {
		Request r = Request.findById(draftId);
		if (r != null) {
			r.delete2();
		}

	}

	/**
	 * @author AbedelRahman Badawy
	 * @param OrgId
	 *            long Id of the organization
	 * @param visibility
	 *            String visibility of the organization this method changes the
	 *            visibility of an organization
	 */
	public static void changeOrgVisibility(long OrgId, String visibility) {
		JsonObject json = new JsonObject();
		Organization org = (Organization) Organization.findById(OrgId);
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());

		boolean flag = false;
		for (int i = 0; i < org.managers.size(); i++) {
			if (org.managers.get(i).ideaDeveloper.equals(idev)) {
				flag = true;
				break;
			}

		}

		if (flag) {
			org.type = visibility;
			org.save();
			IdeaDeveloper admin = (IdeaDeveloper) IdeaDeveloper
					.find("username=?", "administrator").fetch().get(0);
			Notification.notify(
					"has changed the visibility of the organization "
							+ org.name + " to " + org.type, admin, idev,
					new Date());
			json.addProperty("box", "Visibility changed to " + org.type);
		} else {
			json.addProperty("box",
					"Operation not allowed!! You are not the lead of the organization");
		}

		renderJSON(json.toString());
	}

	/**
	 * @author AbedelRahman Badawy this methods creates a new TopicRelation and
	 *         saves it in the database. It also checks whether the relation
	 *         already exists.
	 * @param firstId
	 *            long Id of the first topic
	 * @param secondName
	 *            String title of the second topic
	 * @param body
	 *            String description of the relation
	 * @param name
	 *            String name of the relation
	 */
	public static void addRelationtoTopic(long firstId, String secondName,
			String body, String name) {
		JsonObject json = new JsonObject();
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		Topic temp = Topic.find("title=?", secondName).first();

		Organization org = temp.orgWhereTopicExist();
		boolean flag = false;
		for (int i = 0; i < org.managers.size(); i++) {
			if (org.managers.get(i).ideaDeveloper.equals(idev)) {
				flag = true;
				break;
			}

		}
		if (flag) {
			String rend = "No topics selected!!";
			if (temp != null) {
				Topic one = Topic.findById(firstId);
				if(temp.locked==false && one.locked==false){
				rend = TopicRelation.MakeTopicRelation(firstId, temp.id, name,
						body);
				for(int i=0; i<one.followed.size(); i++){
					Notification.notify(" has related the topic <a href='/topicideacontroller/checkAuthorizationToViewTopic?topicId="
								+ one.id + "'>" + one.title + "</a> to the entity <a href='/topicideacontroller/checkAuthorizationToViewTopic?topicId="
								+ temp.id + "'>" + temp.title + "</a>", one.followed.get(i), idev, new Date());
				}
				for(int i=0; i<temp.followed.size(); i++){
					Notification.notify(" has related the topic <a href='/topicideacontroller/checkAuthorizationToViewTopic?topicId="
							+ one.id + "'>" + one.title + "</a> to the entity <a href='/topicideacontroller/checkAuthorizationToViewTopic?topicId="
							+ temp.id + "'>" + temp.title + "</a>", temp.followed.get(i), idev, new Date());
				}
				}
				else{
					rend = "The topic is locked";
				}
			}

			json.addProperty("res", rend);
		} else {
			json.addProperty("res",
					"Operation not allowed!! You are not the lead of the organization");
		}

		renderJSON(json.toString());
	}

	public static void getDraftsE(long entId, long x) {
		int y = (int) x;
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		ArrayList<Request> drafts = new ArrayList<Request>();
		for (int i = 0; i < idev.requests.size(); i++) {
			if (idev.requests.get(i).type.equals("TopicDraft")
					&& idev.requests.get(i).entId == entId) {
				drafts.add(idev.requests.get(i));
			}
		}
		Request r = drafts.get(y);
		JsonObject json = new JsonObject();
		json.addProperty("size", drafts.size());
		json.addProperty("title", r.title);
		json.addProperty("description", r.description);
		json.addProperty("id", r.id);
		renderJSON(json.toString());
	}

	public static void topicRequestEnt(String title, String description,
			long entId) {
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		Entities ent = Entities.findById(entId);
		Request.RequestMe(ent, idev, title, description);
		int s = (Request.find(
				"title=? and description=? and orgId=? and dev=?", title,
				description, entId, idev).fetch()).size();
		if (s != 0) {
			Request r = (Request) Request
					.find("title=? and description=? and orgId=? and dev=?",
							title, description, entId, idev).fetch().get(0);
			if (r != null) {
				r.delete2();
			}
		}
	}

	public static void topicRequestEntSaved(long entId) {
		// IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		JsonObject check = new JsonObject();
		Entities ent = Entities.findById(entId);
		check.addProperty("RequestsinOrg", ent.requests.size());
		renderJSON(check.toString());
	}

	/**
	 * save a draft of a topic request in a certain entity
	 * 
	 * @author Dina
	 * @param title
	 *            title of the drafted topic request
	 * @param description
	 *            description of the drafted topic request
	 * @param entId
	 *            id of the entity
	 */
	public static void saveDraftE(String title, String description, long entId) {
		IdeaDeveloper dev = IdeaDeveloper.findById(Security.userid());
		Request.draftMeEnt(title, description, dev, entId);
	}

	/**
	 * checks the authorization of the logged in user on an entity to display
	 * buttons
	 * 
	 * @author Dina
	 * @param entId
	 *            id of the entity
	 */
	public static void checkForButtonsE(long entId) {
		IdeaDeveloper dev = IdeaDeveloper.findById(Security.userid());
		Entities ent = Entities.findById(entId);
		JsonObject checkButtons = new JsonObject();
		ArrayList<IdeaDeveloper> leads = new ArrayList<IdeaDeveloper>();
		for (int i = 0; i < ent.managers.size(); i++) {
			leads.add(ent.managers.get(i).ideaDeveloper);
		}
		checkButtons.addProperty("leaders", leads.contains(dev));
		renderJSON(checkButtons.toString());
	}

	/**
	 * check for the draft lost of topic requests whether it's empty or not and
	 * return the result a JSonObject to the view
	 * 
	 * @Author Dina
	 * @param entId
	 *            id of the entity
	 */
	public static void draftsButtonsE(long entId) {
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		ArrayList<Request> drafts = new ArrayList<Request>();
		for (int i = 0; i < idev.requests.size(); i++) {
			if (idev.requests.get(i).type.equals("TopicDraft")
					&& idev.requests.get(i).entId == entId) {
				drafts.add(idev.requests.get(i));
			}
		}
		JsonObject json = new JsonObject();
		json.addProperty("draftsEmpty", drafts.isEmpty());
		renderJSON(json.toString());
	}

	/**
	 * get a request in an entity given its index of the request in the list
	 * 
	 * @author Dina
	 * @param entId
	 *            id of the entity
	 * @param x
	 *            index of the request
	 */
	public static void getRequestsE(long entId, long x) {
		Entities ent = Entities.findById(entId);
		int i = (int) x;
		JsonObject json = new JsonObject();
		json.addProperty("size", ent.requests.size());
		if (!ent.requests.isEmpty()) {
			Request r = ent.requests.get(i);
			json.addProperty("x", i);
			json.addProperty("name", r.dev.username);
			json.addProperty("title", r.title);
			json.addProperty("description", r.description);
			json.addProperty("id", r.id);
		}
		renderJSON(json.toString());

	}

	public static void entityViewByName(String entityName) {
		try {
			Entities entity = Entities.find("name=?", entityName).first();
			EntityView(entity.id);
		} catch (Exception e) {
			return;
		}
	}

	   /**
     * @author Ousama
     * @param devId
     *            the id of the developer of the adder
     * @param orgName
     *            the name of the new organization
     * @param description
     *            the description of the organization
     * @param type
     *            the type of the organization
     */
    public static void createOrganization(long devId, String orgName,
            String description, String type) {
        JsonObject json = new JsonObject();
        if (Organization.count("name = ?", orgName) > 0) {
            json.addProperty("res", "This Name is Not avaliable :)");
        } else {
            IdeaDeveloper devloper = IdeaDeveloper.findById(devId);
            Organization.create(devloper, orgName, description, type);
            devloper.incrementCounter(10);
            json.addProperty("res", "Done Adding");
        }

        renderJSON(json.toString());
    }

    /**
     * @author Ousama this method for adding a picture to a profile of a user
     * @param picture
     *            the Pircture to be uploaded
     * @param id
     *            the id of the developer that uploaded the picture to his
     *            profile
     * @param type
     *            that says this is a profile picture or an Organization Picture
     */
    public static void uploadPicture(Picture picture, long id, String type) {
        IdeaDeveloper currentIdeaDeveloper = IdeaDeveloper.find("id=?",
                Security.userid()).first();
        picture.userId = currentIdeaDeveloper.id;
        picture.type = type;
        picture.save();
        slideShow();
    }

    /**
     * @author Ousama opens the slideShow Images for a user
     */
    public static void slideShow() {
        IdeaDeveloper currentIdeaDeveloper = IdeaDeveloper.find("id=?",
                Security.userid()).first();
        long id = currentIdeaDeveloper.id;
        String name = currentIdeaDeveloper.username;
        render(id, name);
    }

    /**
     * @author Ousama
     * @param id
     *            the developer which we are searching for his pics
     */
    public static void getPicture(long id) {
        Picture picture = Picture.findById(id);
        response.setContentTypeIfNotSet(picture.image.type());
        renderBinary(picture.image.get());
    }

    public static List<Picture> getOrgPics(long id) {
        ArrayList<Picture> pics = new ArrayList<Picture>();
        OrganizationLead leader = OrganizationLead.find("ideaDeveloper.id = ?",
                id).first();
        for (int i = 0; i < leader.manages.size(); i++) {
            List<Picture> pics2 = Picture.find("userId = ? and type = ?",
                    leader.manages.get(i).id, "org").fetch();
            pics.addAll(pics2);
        }
        return pics;
    }

	/**
	 * @author AbedelRahman Badawy This method creates a relation between two
	 *         entities. It also checks whether this relation already exists.
	 * @param firstId
	 *            long Id of the first Entity
	 * @param secondName
	 *            String title of the second Entity
	 * @param body
	 *            String description of the relation
	 * @param name
	 *            String name of the relation
	 */

	public static void addRelationtoEntity(long firstId, String secondName,
			String body, String name) {
		JsonObject json = new JsonObject();
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());

		Entities temp = (Entities) Entities.find("name=?", secondName).fetch()
				.get(0);
		Organization org = temp.liesIn;
		boolean flag = false;
		for (int i = 0; i < org.managers.size(); i++) {
			if (org.managers.get(i).ideaDeveloper.equals(idev)) {
				flag = true;
				break;
			}

		}
		if (flag) {
			String rend = "No Entities selected!!";
			if (temp != null) {
				Entities one = Entities.findById(firstId);
				if(temp.locked==false && one.locked==false){
				rend = EntityRelation.MakeEntityRelation(firstId, temp.id,
						name, body);
				for(int i=0; i<one.followed.size(); i++){
					Notification.notify(" has related the entity <a href='/application/entityview?entityId="
								+ one.id + "'>" + one.name + "</a> to the entity <a href='/application/entityview?entityId="
								+ temp.id + "'>" + temp.name + "</a>", one.followed.get(i), idev, new Date());
				}
				for(int i=0; i<temp.followed.size(); i++){
					Notification.notify(" has related the entity <a href='/application/entityview?entityId="
							+ one.id + "'>" + one.name + "</a> to the entity <a href='/application/entityview?entityId="
							+ temp.id + "'>" + temp.name + "</a>", temp.followed.get(i), idev, new Date());
				}
				// rend = temp.id+"";
				}
				else{
					rend = "Entity is locked!!";
				}
			}

			json.addProperty("res", rend);
		} else {
			json.addProperty("res",
					"Operation not allowed! You are not the lead of the organization");
		}

		renderJSON(json.toString());
	}

	/**
	 * @author AbedelRahman Badawy this method removes the relation between two
	 *         entities.
	 * @param entityIdOne
	 *            long Id of the first entity
	 * @param relationName
	 *            String relation name
	 */
	public static void removeEntityRelation(long entityIdOne,
			String relationName) {
		JsonObject json = new JsonObject();
		IdeaDeveloper idev = IdeaDeveloper.findById(Security.userid());
		Entities one = Entities.findById(entityIdOne);
		EntityRelation c = (EntityRelation) EntityRelation
				.find("select tr from EntityRelation tr where tr.firstEntity=? or tr.secondEntity =? and tr.relationName=?",
						entityIdOne, entityIdOne, relationName).fetch().get(0);

		Organization org = one.liesIn;
		boolean flag = false;
		for (int i = 0; i < org.managers.size(); i++) {
			if (org.managers.get(i).ideaDeveloper.equals(idev)) {
				flag = true;
				break;
			}

		}
		if (flag) {

			String x = EntityRelation.DelteRelationsEntity(c.id);
			json.addProperty("box", x);
		} else {
			json.addProperty("box",
					"Operation not allowed!! You are not the lead of the organization");
		}
		renderJSON(json.toString());
	}

	/**
	 * @author Ousama this method to tell the view of the organization if the
	 *         developer in it now is an Organizationlead or not so we can show
	 *         him the create Entitiy in it
	 * @param orgId
	 *            the id of the organization we want to check
	 */
	public static void getType(long orgId) {
		Organization org = Organization.findById(orgId);
		String connectedUser = Security.connected();
		OrganizationLead checkedDeveloper = OrganizationLead.find(
				"ideaDeveloper.username=?", connectedUser).first();
		JsonObject json = new JsonObject();
		if (checkedDeveloper == null
				|| !org.managers.contains(checkedDeveloper)) {
			json.addProperty("res", "False");
		} else {
			json.addProperty("res", "True");
		}
		renderJSON(json.toString());
	}

	public static void resOrganizersTopic(long topicID, String organizerName) {
		JsonObject json = new JsonObject();
		Organizer organizer = new Organizer();
		Topic topic = Topic.find("id =?", topicID).first();
		for (int i = 0; i < Organizer.findAll().size(); i++) {
			if ((((Organizer) Organizer.findAll().get(i)).ideaDeveloper.username)
					.equals(organizerName)) {
				organizer = (Organizer) Organizer.findAll().get(i);
				break;
			}
		}
		json.addProperty("res",
				OrganizationLead.restrictAccessTopic(organizer, topic));
		renderJSON(json.toString());
	}

	public static void getOrganizersTopic(long topicID) {
		JsonObject json = new JsonObject();
		String s = "*";
		try {
			Topic topic = Topic.find("id =?", topicID).first();
			boolean creatorAdded = false;
			for (int i = 0; i < topic.managers.size(); i++) {
				if (!s.contains(topic.managers.get(i).ideaDeveloper.username)) {
					json.addProperty("topicID",
							topic.managers.get(i).id.toString());
					s += topic.managers.get(i).ideaDeveloper.username + "*";
					if (topic.managers.get(i).ideaDeveloper == topic.creator)
						creatorAdded = true;
				}
			}
			if (!creatorAdded) {
				s += topic.creator.username;
			}

		} catch (Exception e) {
			json.addProperty("res", "matrunesh");
		}
		json.addProperty("res", s);
		renderJSON(json.toString());
	}

	public static void tareq() {
		render();
	}

	/**
	 * deletes the organization that the organization lead is standing in in the
	 * site and notifies the followers before deleting
	 * 
	 * @author nataly.wadie
	 * @param organizationId
	 *            organization id that the organization lead is deleting
	 */
	public static void deleteOrganization(long organizationId) {
		Organization organization = Organization.findById(organizationId);
		JsonObject deleteOrganization = new JsonObject();
		for (int i = 0; i < organization.followed.size(); i++) {
			Notification.notify("has deleted the organization called "
					+ organization.name, organization.followed.get(i),
					organization.creator.ideaDeveloper, new Date());
		}
		organization.delete2();
		deleteOrganization.addProperty("deleteOrganization", "deleted");
		renderJSON(deleteOrganization.toString());
	}

	/**
	 * @author Ousama
	 * @param devId
	 *            the developer which we want to get the topics he manages
	 */
	public static void getManagedTopics(long devId) {
		Organizer orgz = Organizer.find("ideaDeveloper.id =", devId).first();
		if (orgz == null) {
			renderJSON(null);
		} else {
			ArrayList<rendering> rendering = new ArrayList<rendering>();
			for (int i = 0; i < orgz.managedTopics.size(); i++) {
				if (orgz.managedTopics.get(i).topicEnt != null) {
					rendering.add((new rendering("TOPIC "
							+ orgz.managedTopics.get(i).title + " in entity "
							+ orgz.managedTopics.get(i).topicEnt.name
							+ " in organization "
							+ orgz.managedTopics.get(i).topicEnt.liesIn.name,
							orgz.managedTopics.get(i).id)));
				} else {
					rendering.add((new rendering("TOPIC "
							+ orgz.managedTopics.get(i).title
							+ " in organization "
							+ orgz.managedTopics.get(i).topicEnt.liesIn.name,
							orgz.managedTopics.get(i).id)));
				}
			}
			renderJSON(rendering);
		}
	}

	/**
	 * @auhor Ousama
	 * @param topicId
	 *            the topic which we want to get the developers that can be
	 *            requested to be organizer on it
	 */
	public static void getCanBeTopicManager(long topicId) {
		Topic topic = Topic.findById(topicId);
		List<IdeaDeveloper> devs = IdeaDeveloper.findAll();
		for (int i = 0; i < topic.managers.size(); i++) {
			devs.remove(topic.managers.get(i).ideaDeveloper);
		}
		if (topic.topicEnt != null) {
			for (int i = 0; i < topic.topicEnt.blocked.size(); i++) {
				devs.remove(topic.topicEnt.blocked.get(i));
			}
			for (int i = 0; i < topic.topicEnt.liesIn.blocked.size(); i++) {
				devs.remove(topic.topicEnt.liesIn.blocked.get(i));
			}
		} else {
			for (int i = 0; i < topic.topicOrg.blocked.size(); i++) {
				devs.remove(topic.topicOrg.blocked.get(i));
			}
		}

		for (int i = 0; i < topic.requests.size(); i++) {
			devs.remove(topic.requests.get(i).dev);
		}
		String result = "";
		for (int i = 0; i < devs.size() - 1; i++) {
			result += devs.get(i).username + "&&";
		}
		result += devs.get(devs.size() - 1).username;
		JsonObject json = new JsonObject();
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	/**
	 * @author Ousama
	 * @param topicId
	 *            the topic we want to request a developer to be manager on
	 * @param devName
	 *            the name of the developer that we want to make him a manager
	 *            on the given topic
	 */
	public static void requestIdeaDeveloperToTopic(long topicId, String devName) {
		JsonObject json = new JsonObject();
		try {
			IdeaDeveloper dev = IdeaDeveloper.find("username = ?", devName)
					.first();
			Topic topic = Topic.findById(topicId);
			boolean add = false;
			for (int i = 0; i < topic.managers.size(); i++) {
				if (topic.managers.get(i).ideaDeveloper.equals(dev)) {
					json.addProperty("res", "already a manager");
					renderJSON(json.toString());
					add = true;
					break;
				}
			}
			for (int i = 0; !add && topic.topicEnt != null
					&& i < topic.topicEnt.blocked.size(); i++) {
				if (topic.topicEnt.blocked.get(i).equals(dev)) {
					json.addProperty("res", "Blocked from the entity");
					renderJSON(json.toString());
					add = true;
					break;
				}
			}
			for (int i = 0; !add && topic.topicEnt != null
					&& i < topic.topicEnt.liesIn.blocked.size(); i++) {
				if (topic.topicEnt.liesIn.blocked.get(i).equals(dev)) {
					json.addProperty("res", "Blocked from the Organization");
					renderJSON(json.toString());
					add = true;
					break;
				}
			}
			for (int i = 0; !add && topic.topicOrg != null
					&& i < topic.topicOrg.blocked.size(); i++) {
				if (topic.topicOrg.blocked.get(i).equals(dev)) {
					json.addProperty("res", "Blocked from the Organization");
					renderJSON(json.toString());
					add = true;
					break;
				}
			}
			for (int i = 0; !add && i < topic.requests.size(); i++) {
				if (topic.requests.get(i).dev.equals(dev)) {
					json.addProperty("res", "ALREADY INVITED");
					renderJSON(json.toString());
					add = true;
					break;
				}
			}
			if (!add) {
				Request.requestMe(topic, dev);
				json.addProperty("res", "DONE");
				renderJSON(json.toString());
			}
		} catch (Exception e) {
			json.addProperty("res", "Invalid username");
			renderJSON(json.toString());
		}
	}

	public static void slideShowOrg(long orgId) {
		Organization org = Organization.findById(orgId);
		String name = org.name;
		render(name, orgId);
	}

	public static void uploadPictureOrg(Picture picture, String type, long orgId) {
		picture.type = type;
		picture.userId = orgId;
		picture.save();
	}

      /**
     * @author Ousama
     * @param reqId the request that we want to delete or decline
     */
    public static void declineRequest(long reqId) {
        Request req = Request.findById(reqId);
        String toReturnString = req.Decline();
        JsonObject json = new JsonObject();
        json.addProperty("res", toReturnString);
        renderJSON(json.toString());
    }
}
